#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
#include <unistd.h>

const int num = 5;

void* threadRun(void* args)
{
    // pthread_detach(pthread_self());

    std::string name = static_cast<const char*> (args);
    while(true)
    {
        std::cout << name << " is running..." << std::endl;
        sleep(3);
        break;
    }
    //return args;
    pthread_exit(args);
}

std::string PrintToHex(pthread_t &tid)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", tid);
    return buffer;
}


int main()
{
    std::vector<pthread_t> tids;
    for(int i = 0; i < num; ++i)
    {
        pthread_t tid;
        char *name = new char[128];

        snprintf(name, 128, "thread-%d", i);
        pthread_create(&tid, nullptr, threadRun, name);
        tids.emplace_back(tid);
    }

    for(auto tid : tids)
    {
        pthread_detach(tid);
    }

    for(auto tid : tids)
    {
        // pthread_cancel(tid);
        // std::cout << "cancel: " << PrintToHex(tid) << std::endl;
        void* result = nullptr;
        //std::cout << PrintToHex(tid) << " quit..." << std::endl;

        int n = pthread_join(tid, &result); //线程被取消返回的结果是-1
        std::cout << (long long int)result << " quit..., n = " << n << std::endl;
        // delete (const char*)name;
    }

    //sleep(100);
    return 0;
}
